#include <stdio.h>
#include <unistd.h> 
#include <arpa/inet.h>

#include <checks.h>
#include <network.h>
#include <server.h>

struct game *createGame(struct client *, char[]);

void *lobby(void *clientura){
	struct client *client = clientura;
	printf("Клиент %s/%d зашёл в лобби.\n", client->ip, client->id);
	char *receiveMessage;
	int code;
	while((client->sockfd > 0) && ((recv(client->sockfd, &code, sizeof(int), MSG_PEEK)) > 0)){
		receiveMessage = receiving(client->sockfd);	
		switch(code){
			case CREATEGAME:{
				if (receiveMessage == NULL){
					sending(client->sockfd, WRONGCODE, NULL);
					break;
				}
				struct game *combat;
				if((combat = createGame(clientura, receiveMessage)) == NULL){
					sending(client->sockfd, MAXGAMES, NULL); 
					break;
				}
				sending(client->sockfd, CREATEOK, NULL);
				inGame(combat, client);
				break;
			}
			case JOINGAME:{
				if (receiveMessage == NULL){
					sending(client->sockfd, WRONGGAME, NULL);
					break;
				}
				int number = atoi(receiveMessage);	
				if (games[number].play != 1){
					sending(client->sockfd, WRONGGAME, NULL);
					break;
				}
				games[number].play = 2;
				games[number].black = clientura; // <-
				sending(games[number].white->sockfd, STARTGAME, NULL);
				sending(games[number].black->sockfd, STARTGAME, NULL);
				if(inGame(&games[number], client) < 0){
					return;
				}
				break;
			}
			case GAMELIST:{
				sendGameList(client->sockfd);
				break;
			}
			case WHERE:{
				sending(client->sockfd, YOUHERE, "Лобби.");
				break;
			}
			case ECHOREQ:{
				sending(client->sockfd, ECHOREQ, receiveMessage);
				break;
			}
			default:{
				sending(client->sockfd, WRONGCODE, NULL);
				printf("Читак %s/%d выброшен из сервера.\n", client->ip, client->id);
				shutdown(client->sockfd, 2);
				close(client->sockfd);
				return;
				break;
			}
		}
	}
	printf("Клиент %s/%d отключился от сервера.\n", client->ip, client->id);
	if (client->sockfd > 0){
		close(client->sockfd);
	}
	client->sockfd = -1;
	return 0;
}
